"""
序列化
"""
from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator


from .models import UserFav, UserLeavingMessage, UserAddress
from goods.serializers import GoodsSerializer


class UserFavSerializer(serializers.ModelSerializer):

    # 获取到当前用户
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )

    class Meta:
        model = UserFav

        validators = [
            UniqueTogetherValidator(
                queryset=UserFav.objects.all(),
                fields=('user', 'goods',),
                message="已经收藏过了"  # 联合索引出错时，打印信息
            )
        ]

        fields = ("user", "goods", "id",)  # 需要做删除功能的话，需要将ID加入


class UserFavDetailSerializer(serializers.ModelSerializer):

    goods = GoodsSerializer()  # 外键嵌套 Serializer

    class Meta:
        model = UserFav
        fields = ("goods", "id")


class LeavingMessageSerializer(serializers.ModelSerializer):

    # 获取到当前用户
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )

    add_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M')  # 设置为不可提交，只可获取

    class Meta:
        model = UserLeavingMessage
        fields = ("user", "message_type", "subject", "message", "file", "id", "add_time")


class AddressSerializer(serializers.ModelSerializer):

    # 获取到当前用户
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )

    add_time = serializers.DateTimeField(read_only=True)  # 设置为不可提交，只可获取

    class Meta:
        model = UserAddress
        fields = "__all__"
